task default: [
  'gem:all'
]

namespace :gem do

  desc "install the gem on the local machine"
  task :install do
    sh "gem install #{PARAMS[:gemspec].name}"
    sh "gem cleanup #{PARAMS[:gemspec].name}"
    sh "rubygems_my_setup"
  end

  desc "publish the gem"
  task :push do
    sh 'gem push *.gem'
  end

  desc "publish the gem"
  task all: [:push]

end


# Task parameters ##################################
PARAMS = {
  gemspec:   nil
}

# Capture gem specification by 'eval'ing the *.gemspec file
# using a fake Gem::Specification class
begin
  require 'ostruct'
  require 'pathname'

  module Gem
    # Fake Gem::Specification class
    class Specification
      def initialize 
        @spec = OpenStruct.new
        @spec.executables = []
        @spec.metadata = {}
        @spec.development_dependencies = []
        @spec.singleton_class.class_eval do
          def add_development_dependency *geminfo
            self.development_dependencies << geminfo
          end
        end

        yield @spec
        #$stderr.puts "#{@spec.inspect}" 
        ::PARAMS[:gemspec] = @spec
      end
    end
  end

  def read_gemspec
    gemspec = Dir['../*/*.gemspec'].first
    return unless gemspec
    gemspec = Pathname.new(gemspec)
    return unless gemspec.file?
    gemspec = gemspec.read
    self.instance_eval gemspec
  end

  read_gemspec
end
